import axios from "axios";
import { ElMessage } from "element-plus";
import qs from "qs";

// 创建 axios 实例
const service = axios.create({
  baseURL: '/api',
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
  paramsSerializer: (params) => {
    // 过滤掉undefined和null值，避免发送空参数
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([key, value]) =>
        value !== undefined && value !== null && value !== ''
      )
    );
    return qs.stringify(filteredParams, {
      encode: true, // 确保中文字符正确编码
      charset: 'utf-8'
    });
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    //从localStorage中取出accessToken
    //const accessToken = getAccessToken();
    //config.headers.Authorization = `Bearer ${accessToken}`;
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 如果后端返回标准格式 {flag, data, msg}
    if (response.data && typeof response.data === 'object' && 'flag' in response.data) {
      const { flag, data, msg } = response.data;
      if (flag == true) {
        return data;
      }
      ElMessage.error(msg || "系统出错");
      return Promise.reject(new Error(msg || "Error"));
    }

    // 如果后端直接返回数据数组或对象，直接返回
    return response.data;
  },
  async (error) => {
    console.error("request error", error); // for debug
    const { config, response } = error;
    if (response && response.data) {
      // 尝试解析错误消息
      const errorMsg = response.data.msg || response.data.message || `HTTP ${response.status} 错误`;
      ElMessage.error(errorMsg);
    } else {
      ElMessage.error("网络连接失败，请检查后端服务是否启动");
    }
    return Promise.reject(error.message || error);
  }
);

export default service;